
import hashlib

from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired, BadSignature
from flask import current_app
from sqlalchemy import Column, Integer, VARCHAR, Text, Integer


from hzb.database import db
from hzb.wx.wx_unionid_manage import WxUnionIdManageModel


class UsersModel(db.Model):
    __tablename__ = 'hzb_user'

    id = Column(db.Integer, primary_key=True)
    icon = Column('icon', VARCHAR(length=255), comment='用户头像地址')
    name = Column('name', VARCHAR(length=255), comment='用户昵称')
    create_time = Column('create_time', Integer, comment='用户创建时间')
    sex = Column('sex', Integer, comment="用户性别")
    city = Column('city', VARCHAR(length=255), comment='用户城市')
    wx_union_id = Column('wx_union_id', VARCHAR(length=255), comment="微信用户的union_id")

    def __init__(self):
        # self.created_ts = int(time.time())
        # self.updated_ts = self.created_ts
        pass

    # 定义过期期限
    def generate_auth_token(self, expiration=259200):
        s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration)
        return s.dumps({'id': self.id}).decode('utf-8')

    def verify_password(self, union_id):
        # 进行登录查询
        union_id = WxUnionIdManageModel.query.filter_by(union_id=union_id).first()
        if union_id is not None:
            return True
        print("UsersModel verify_password failed!")
        return False

    # 判断token，token如果没过期，则返回对应的user
    @staticmethod
    def verify_auth_token(token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except SignatureExpired:
            return None  # valid token, but expired
        except BadSignature:
            return None  # invalid token
        user = UsersModel.query.get(data['id'])
        # 判断token字符串的一致性，后续判断单点登录
        return user

